use actix_files as fs;
use actix_web::http::header::{ContentDisposition, DispositionParam, DispositionType};
use actix_web::{get, Error, HttpRequest,client::{Client}};
use std::fs::File;
use std::path::Path;
use std::process::Command;
use uuid::Uuid; // 引入命令模块
use qstring::QString;
use std::time::{Duration};
async fn downloadFile(source_filename :&String ,url :String) {
    let client = Client::builder().finish();
    let bytes =
        client
        
        .get(url.to_owned())
        //下载超时时间
        .timeout(Duration::from_secs(60))
        .send()
        .await
        .unwrap()
        .body()
        .await
        .unwrap();
        

    let path = Path::new(&source_filename);
    let display = path.display();
    let mut file = File::create(&path).unwrap();
    match std::io::copy(&mut &bytes[..], &mut file) {
        Err(why) => println!("couldn't write to {}: {}", display, why),
        Ok(_) => println!("successfully wrote to {}", display),
    };
} 
//pdf转换
#[get("/pdfconvert")]
pub async fn pdfconvert(req: HttpRequest) -> Result<fs::NamedFile, Error> {
    //临时目录创建
    match std::fs::create_dir("/tmp") {
        Err(why) => println!("! {:?}", why.kind()),
        Ok(_) => {}
    };
    //源文件地址
    let source_filename: String = format!("/tmp/{}", Uuid::new_v4());
    //目标转换pdf地址
    let target_filepath: String = String::from("/tmp");

    //源文件url
    let query_str = req.query_string();
    let qs = QString::from(query_str);
    let url = qs.get("url").unwrap();
    println!("url={}",url.to_owned());
    //http客户端
    //文件下载
    downloadFile(&source_filename, url.to_owned()).await;
    
    //todo 文件转换pdf 使用 libreoffice
    println!(
        "libreoffice --headless --convert-to pdf --outdir {} {}",
        
        target_filepath.to_owned(),
        source_filename.to_owned()
    );
    Command::new("sh").arg("-c").arg(format!(
        "libreoffice --headless --convert-to pdf --outdir {} {}",
        target_filepath.to_owned(),
        source_filename.to_owned()
    )).output()
    .expect("command failed to start");


    println!("response {}.pdf",source_filename.to_owned());


    //todo 输出pdf文件
    let target_file = fs::NamedFile::open(format!("{}.pdf",source_filename.to_owned()))?;

    

    Ok(target_file
        .use_last_modified(true)
        .set_content_type("application/pdf".parse().unwrap())
        .set_content_disposition(ContentDisposition {
            disposition: DispositionType::Attachment,
            parameters: vec![DispositionParam::Filename(String::from("转换pdf文件.pdf"))],
        }))
}
